#!/usr/bin/env bash

# install sshpass
# ssh-keygen if id_rsa.pub not exists
# upload id_rsa.pub to remote server

LOG_WARN()
{
    local content=${1}
    echo -e "\033[31m[WARN] ${content}\033[0m"
}

LOG_INFO()
{
    local content=${1}
    echo -e "\033[32m[INFO] ${content}\033[0m"
}

# 命令返回非 0 时，就退出
set -o errexit
# 管道命令中任何一个失败，就退出
set -o pipefail
# 遇到不存在的变量就会报错，并停止执行
set -o nounset
# 在执行每一个命令之前把经过变量展开之后的命令打印出来，调试时很有用
#set -o xtrace

# 退出时，执行的命令，做一些收尾工作
trap 'echo -e "Aborted, error $? in command: $BASH_COMMAND"; trap ERR; exit 1' ERR

# Set magic variables for current file & dir
# 脚本所在的目录
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# 脚本的全路径，包含脚本文件名
__file="${__dir}/$(basename "${BASH_SOURCE[0]}")"
# 脚本的名称，不包含扩展名
__base="$(basename ${__file} .sh)"
# 脚本所在的目录的父目录，一般脚本都会在父项目中的子目录，
#     比如: bin, script 等，需要根据场景修改
__root="$(cd "$(dirname "${__dir}")" && pwd)" # <-- change this as it depends on your app
# install sshpass

host=
port=22
user=root
password=
method=
rsa=

####### error code
SUCCESS=0
PARAM_ERROR=2

####### 参数解析 #######
cmdname=$(basename "$0")

# usage help doc.
usage() {
    cat << USAGE  >&2
Usage:
    $cmdname [-H host] [-P port] [-u user] [-p password] [-r rsaFile] [-m method] [-h]
    -H     Required, remote host.
    -P     Not required, remote port, default is 22.
    -u     Not required, remote userName, default is root.
    -p     Required, password.
    -r     Not Required, SSH rsa private key file.
    -m     Specify the method to be executed,  chose:checkHost、checkWebaseImages、checkFabricImages
    -h     Show help info.
USAGE
    exit ${PARAM_ERROR}
}


while getopts H:P:u:p:r:m:h OPT;do
    case ${OPT} in
        H)
            host=$OPTARG
            ;;
        P)
            port=$OPTARG
            ;;
        u)
            user=$OPTARG
            ;;
        p)
            password=$OPTARG
            ;;
        r)
            rsa=$OPTARG
            ;;
        m)
            method=$OPTARG
            ;;
        h)
            usage
            exit ${PARAM_ERROR}
            ;;
        \?)
            usage
            exit ${PARAM_ERROR}
            ;;
    esac
done

echo "host operate, ${user}@${host}:${port}#${password}..."
echo "method:[${method}]"

if [ "" == "${method}" ]; then
    echo "method can not be null!!"
    exit -1
fi



use_rsa=
if [[ $rsa ]] ; then
    use_rsa=" -i ${rsa}"
fi
echo ${use_rsa}


function sshExec(){
    ssh ${use_rsa} -q -o "StrictHostKeyChecking=no" \
    -o "LogLevel=ERROR" \
    -o "UserKnownHostsFile=/dev/null" \
    -o "PubkeyAuthentication=yes" \
    -o "PasswordAuthentication=no" \
     "${user}"@"${host}" -p "${port}" $@
}


function check_ssh(){
  target_ip=$1
  target_port=$2
  current_user=$3

  nport=`timeout 5 ssh -p${target_port} ${current_user}@${target_ip} ${use_rsa} 'echo "0"' 2>&1` || :
  if [[ "$nport" == "0" ]];then
    echo "ssh connect success"
  else
    echo "ssh connect not success"
    exit -1
  fi
}


function checkHost() {
    # check host
      cat "${__dir}/check_hosts.sh" | sshExec bash -e -x
      status=($?)
      if [[ $status != 0 ]] ;then
          echo "Remote check host not success!!!!"
          exit "$status"
      fi
}


# check host
check_ssh ${host} ${port} ${user}
#init
${method}
exit ${SUCCESS}


